const path = require('path');
const fs = require('fs');
const { createLogger, format, transports } = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');

// Ensure logs directory exists
const logsDir = path.join(__dirname, '../../logs');
if (!fs.existsSync(logsDir)) {
  fs.mkdirSync(logsDir, { recursive: true });
}

// Determine log level by environment with override
const env = process.env.APP_ENV || process.env.NODE_ENV || 'development';
const level = process.env.LOG_LEVEL || (env === 'production' || env === 'staging' ? 'info' : 'debug');

const baseFormat = format.combine(
  format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  format.errors({ stack: true }),
  format.splat(),
  format.printf((info) => `${info.timestamp} [${info.level.toUpperCase()}] ${info.message}${info.stack ? '\n' + info.stack : ''}`)
);

const logger = createLogger({
  level,
  format: baseFormat,
  transports: [
    new transports.Console({
      level,
      format: format.combine(
        format.colorize(),
        format.timestamp({ format: 'HH:mm:ss' }),
        format.printf((info) => `${info.timestamp} [${info.level}] ${info.message}`)
      )
    }),
    new DailyRotateFile({
      level: 'info',
      dirname: logsDir,
      filename: 'app-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      zippedArchive: false,
      maxSize: '20m',
      maxFiles: '14d'
    }),
    new DailyRotateFile({
      level: 'error',
      dirname: logsDir,
      filename: 'error-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      zippedArchive: false,
      maxSize: '20m',
      maxFiles: '30d'
    })
  ],
  exitOnError: false
});

// Access log (for morgan)
const accessLogger = createLogger({
  level: 'info',
  format: format.combine(
    format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
    format.printf((i) => `${i.timestamp} ${i.message.trim()}`)
  ),
  transports: [
    new DailyRotateFile({
      dirname: logsDir,
      filename: 'access-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      zippedArchive: false,
      maxSize: '50m',
      maxFiles: '14d'
    })
  ]
});

// Morgan stream
const morganStream = {
  write: (message) => accessLogger.info(message.replace(/\n$/, ''))
};

module.exports = { logger, morganStream };